﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PSS4Publish.Common;
using PSS4Publish.Repositories;

namespace PSS4Publish.AppManagement
{
    public partial class ApplicationPoolManagement : Form
    {
        ApplicationPoolRepository appPoolRepository = new ApplicationPoolRepository();

        string ApplicationPoolName
        {
            get
            {
                if (string.IsNullOrEmpty(cmbSites.SelectedValue.ToString()))
                    return string.Empty;
                else
                    return cmbSites.SelectedValue.ToString();
            }
        }
        public ApplicationPoolManagement()
        {
            InitializeComponent();
        }

        private void ApplicationPoolManagement_Load(object sender, EventArgs e)
        {
            string[] websites = IISWebsite.ExistedWebsites;
            cmbSites.DataSource = websites;
        }

        private void ClearForm()
        {
            txtPath1.Text = txtPath2.Text = string.Empty;
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ApplicationPoolName))
            {
                PSS4PublishEntities db = new PSS4PublishEntities();
                ApplicationPool appPool = appPoolRepository.GetPoolByName(ApplicationPoolName);
                if (appPool != null)
                {
                    txtPath1.Text = appPool.Path1;
                    txtPath2.Text = appPool.Path2;
                }
                else
                {
                    IISWebsite website = IISWebsite.OpenWebsite(cmbSites.SelectedValue.ToString());
                    txtPath1.Text = website.Root.Path;
                }

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ApplicationPoolName) && !string.IsNullOrEmpty(txtPath1.Text) && !string.IsNullOrEmpty(txtPath2.Text))
            {
                ApplicationPool appPool = appPoolRepository.GetPoolByName(ApplicationPoolName);

                if (appPool == null)
                {
                    appPool = new ApplicationPool();
                    appPool.Name = ApplicationPoolName;
                    appPool.Path1 = txtPath1.Text;
                    appPool.Path2 = txtPath2.Text;
                    appPoolRepository.Add(appPool);
                }
                else
                {
                    appPool.Path1 = txtPath1.Text;
                    appPool.Path2 = txtPath2.Text;
                    appPoolRepository.Edit(appPool);
                }

                appPoolRepository.Save();
                ClearForm();
            }
        }
    }
}
